/**
 *    Copyright (C) 2008, 2009  Victor Smirnov <aist11@gmail.com>
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License along
 *    with this program; if not, write to the Free Software Foundation, Inc.,
 *    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 *    See LICENSE.exceptions in the root folder of this project for possible
 *    exceptions
 *
 */


package ru.teleology.cubefs.api.reflection;

@NativeType(name = Types.TYPED_TYPE)
public class Typed extends TypeSystem {
	
	private static final int DESTROY_PEER = 0; 
	
	private long handle;
	
	public Typed(long handle, boolean weak) {
		this.handle = handle;
		SetPeer(handle, weak);
//		System.err.println("Create new object "+this.getClass().getName());
	}
	
	public Typed(long handle) {
		this(handle, true);
	}

	public long getHandle() {
		return handle;
	}

	protected void setHandle(long handle) {
		this.handle = handle;
	}
	
	public boolean isInstance(Type type) {
		return IsInstance(handle, type.getHandle());
	}
	
	public boolean managed() {
		return managed(handle);
	}
	
	public Type type() {
		return type(getHandle());		
	}
	
	public static Type type(long handle) {
		long h = typeHandle(handle);
		if (peer(h) != null) {
			return (Type) peer(h);
		}
		else {
			return new Type(h);
		}		
	}
	
	public void destroy() {
		if (handle != 0) {
			destroy(handle);
			handle = 0;
		}
	}
	
	public static Object peer(long handle) {
		return GetPeer(handle);
	}
	
	@Override
	public String toString() {
		return type().name()+"@"+getHandle();
	}
	
	protected synchronized void finalize() {
		//System.out.println("Finalize:  "+this.getClass().getName());
		destroy();
	}
	
	@SuppressWarnings("unused")
	private synchronized void notify(int signal) {
		if (signal == DESTROY_PEER) {
			handle = 0;
		}
	}
	
	private static native boolean IsInstance(long me, long type);
	private static native boolean managed(long me);
	protected static native long typeHandle(long me);
	private static native void destroy(long me);
	
	private static native Object GetPeer(long me);
	private native void SetPeer(long me, boolean weak);
	
	protected static native void initNotifier();
	
	private static native void notifyTest(long me, int signal);
}
